<template>
  <div class="right">
    <div class="box" v-for="item in dishList" :key="item.cate_name">
      <h3>{{item.cate_name}}</h3>
      <ul>
        <li v-for="v in item.dishs" :key="v.id">
          <img :src="v.pic" alt="">
          <div class="bottom">
              <span class="name">{{v.dish_name}}</span>
              <span class="price">￥<strong>{{v.price}}</strong>/份</span>
          </div>
          <span class="iconfont recommend" v-show="v.is_recommend === 1">&#xe60b;</span>
          <div class="edit">
              <span class="iconfont" @click="del(v.id)">&#xe610;</span>
              <span class="iconfont" @click="dialogFormVisible = true;currentId = v.id;currentCate = '';getCurrentDish(v.id)">&#xe64a;</span>
          </div>
        </li>
        <li class="add" @click="dialogFormVisible=true;currentCate = item.cate_name;currentId = '';resetForm('ruleForm')"><span class="iconfont">&#xe608;</span></li>
      </ul>
    </div>
    <!-- 添加和修改菜品的组件 -->
    <el-dialog title="菜品信息" :visible.sync="dialogFormVisible">
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
            <el-form-item label="菜名" prop="name">
              <el-input v-model="ruleForm.name"></el-input>
            </el-form-item>
            <el-form-item label="价格" prop="price">
              <el-input v-model="ruleForm.price"></el-input>
            </el-form-item>
            <el-form-item label="简介" prop="introduce">
              <el-input
                  type="textarea"
                  autosize
                  placeholder="请输入内容"
                  v-model="ruleForm.introduce">
              </el-input>
            </el-form-item>
            <el-form-item label="推荐指数" prop="rate">
                <el-rate v-model="ruleForm.rate"></el-rate>
            </el-form-item>
            <el-form-item label="是否推荐" prop="recommend">
                <el-switch v-model="ruleForm.recommend"></el-switch>
            </el-form-item>
            <el-form-item label="图片" prop="imageUrl">
                <div class="upload el-icon-plus">
                    <input type="file" name="" title="" id="uploadFile" @change="getImage">
                    <img v-if="ruleForm.imageUrl" :src="ruleForm.imageUrl" class="image">
                </div>
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="resetForm('ruleForm')">重 置</el-button>
          <el-button type="primary" @click="submitForm('ruleForm',currentCate,currentId)">确 定</el-button>
        </div>
    </el-dialog>
  </div>
</template>

<script>
import { getDishCateAPI } from '@/api/dishCategoryAPI.js'
import { addDishInfoAPI, delDishInfoAPI, updateDishInfoAPI, getDishInfoAPI } from '@/api/dishInfoAPI.js'
export default {
  name: 'dishManage',
  data () {
    return {
      dishList: [],
      currentCate: '',
      currentId: '',
      avltimer: null,
      dialogFormVisible: false,
      ruleForm: {
        name: '',
        price: '',
        introduce: '',
        rate: 0,
        recommend: false,
        imageUrl: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入菜名', trigger: 'blur' }
        ],
        price: [
          { required: true, message: '请输入价格', trigger: 'blur' }
        ],
        introduce: [
          { required: true, message: '请输入简介', trigger: 'blur' }
        ],
        imageUrl: [
          { required: true, message: '请上传图片', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    del (id) {
      this.$confirm('此操作将永久删除该菜品, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.delDish(id)
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    addSuccess () {
      this.$message({
        message: '添加成功',
        type: 'success'
      })
    },
    modifySuccess () {
      this.$message({
        message: '修改成功',
        type: 'success'
      })
    },
    submitForm (formName, cate, id) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.dialogFormVisible = false
          if (cate !== '' && id === '') {
            this.addDishInfo()
            this.addSuccess()
          } else if (cate === '' && id !== '') {
            this.updateDish()
            this.modifySuccess()
          }
        } else {
          return false
        }
      })
    },
    resetForm (formName) {
      this.$refs[formName].resetFields()
    },
    handleAvatarSuccess (res, file) {
      this.ruleForm.imageUrl = URL.createObjectURL(file.raw)
    },
    getImage (e) {
      var fr = new FileReader()
      var fileData = e.target.files[0]
      fr.readAsDataURL(fileData)
      fr.onload = () => {
        var imgSrc = fr.result
        this.ruleForm.imageUrl = imgSrc
      }
    },
    // 添加菜品（增）
    async addDishInfo () {
      const token = localStorage.getItem('token')
      const data = {
        cate_name: this.currentCate,
        dish_name: this.ruleForm.name,
        price: this.ruleForm.price,
        introduce: this.ruleForm.introduce,
        recommend_rate: this.ruleForm.rate,
        pic: this.ruleForm.imageUrl,
        is_recommend: Number(this.ruleForm.recommend)
      }
      const { data: res } = await addDishInfoAPI(token, data)
      console.log(res)
    },
    // 删除菜品（删）
    async delDish (i) {
      const token = localStorage.getItem('token')
      const data = {
        id: i
      }
      const { data: res } = await delDishInfoAPI(token, data)
      console.log(res)
    },
    // 更新菜品信息（改）
    async updateDish () {
      const token = localStorage.getItem('token')
      const data = {
        id: this.currentId,
        dish_name: this.ruleForm.name,
        price: this.ruleForm.price,
        introduce: this.ruleForm.introduce,
        recommend_rate: this.ruleForm.rate,
        pic: this.ruleForm.imageUrl,
        is_recommend: Number(this.ruleForm.recommend)
      }
      const { data: res } = await updateDishInfoAPI(token, data)
      console.log(res)
    },
    // 获取全部菜品（查）
    async getDishInfo () {
      const dishList = []
      const token = localStorage.getItem('token')
      const { data: res1 } = await getDishCateAPI(token)
      const { data: res } = await getDishInfoAPI(token)
      for (let i = 0; i < res1.data.length; i++) {
        dishList.push({
          cate_name: res1.data[i].cate_name,
          dishs: res.data.filter(item => item.cate_name === res1.data[i].cate_name)
        })
      }
      this.dishList = dishList
    },
    async getCurrentDish (id) {
      const token = localStorage.getItem('token')
      const { data: res } = await getDishInfoAPI(token)
      const currentDish = res.data.find(item => item.id === id)
      this.ruleForm.name = currentDish.dish_name
      this.ruleForm.price = currentDish.price
      this.ruleForm.introduce = currentDish.introduce
      this.ruleForm.rate = currentDish.recommend_rate
      this.ruleForm.recommend = Boolean(currentDish.is_recommend)
      this.ruleForm.imageUrl = currentDish.pic
    }
  },
  created () {
    this.avltimer = setInterval(() => {
      this.getDishInfo()
    }, 50)
  },
  beforeDestroy () {
    clearInterval(this.avltimer)
    this.avltimer = null
  }
}
</script>

<style scoped>
/* .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  } */
.upload{
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
}
.upload:hover{
    border-color: #409EFF;
}
.image{
    width: 178px;
    height: 178px;
    position: absolute;
    left: 0;
    top: 0;
}
#uploadFile{
    width: 178px;
    height: 178px;
    position: absolute;
    left: 0;
    top: 0;
    opacity: 0;
    z-index: 999;
}

.box{
    background: #fff;
    box-shadow: 0 5px 5px rgba(0, 0, 0, .2);
    margin: 0 20px 40px;
    padding: 10px;
    border-radius: 10px;
}
.box h3{
    color: #495057;
    font-size: 30px;
    margin-bottom: 20px;
    padding-left: 10px;
}
.box ul{
    overflow: hidden;
}
.box li{
    width: 300px;
    height: 300px;
    float: left;
    margin: 0 10px 20px;
    border-radius: 5px;
    overflow: hidden;
    position: relative;
}
.box img{
    width: 100%;
    height: 100%;
}
.bottom{
    width: 100%;
    height: 50px;
    line-height: 50px;
    box-sizing: border-box;
    padding: 0 15px;
    display: flex;
    justify-content: space-between;

    background: rgba(0, 0, 0, .5);

    position: absolute;
    bottom: 0;
    left: 0;
    color: #fff;
}
.name{
    font-size: 20px;
}
.price strong{
    color: #ff8400;
    font-size: 20px;
    font-weight: normal;
}

.recommend{
    position: absolute;
    left: 5px;
    top: 5px;
    font-size: 50px;
    color: #ff8400;
}
.edit{
    width: 100%;
    height: 100%;
    position: absolute;
    left: 0;
    top: 0;

    display: flex;
    align-items: center;

    justify-content: space-around;  /* 分散居中对齐 */
    background: rgba(0, 0, 0, .9);
    opacity: 0;
}
.edit span{
    color: #dbdbdb;
    font-size: 80px;
    cursor: pointer;
}
.edit span:hover{
    color: #ff8400;
}
.box li:hover .edit{
    opacity: 1;
    transition: .4s;
}

.add{
    display: flex;
    justify-content: center;
    align-items: center;
    cursor: pointer;
    border: 1px solid #ccc;
}
.add span{
    font-size: 200px;
    color: #ccc;
}
.add:hover{
    background: #eee;
    transition: .3s;
}
</style>
